/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.token.TokenManager;
import com.koorz.interceptor.AuthInterceptor;
import com.koorz.interceptor.CommonsInterceptor;
import com.koorz.jfinal.route.ControllerBind;
import com.koorz.modules.catalog.Label;
import com.koorz.modules.image.Image;
import com.koorz.modules.style.SimilarItems;
import com.koorz.modules.style.SimilarStyles;
import com.koorz.modules.style.Style;
import com.koorz.modules.style.StyleItems;
import com.koorz.modules.user.User;
import com.koorz.utils.ActionUtils;
import com.koorz.utils.DateUtil;
import com.koorz.utils.ImageUtil;
import com.koorz.utils.OperateImage;
import com.koorz.utils.SessionContext;
import com.koorz.utils.SystemConfig;

/**
 * 功能描述：搭配
 * 作        者：尹东东 
 * 创建时间：2013-6-2 下午2:39:55
 * 版  本  号：1.0
 */
@ControllerBind(controllerKey = "/style", viewPath = "/")
public class StyleController extends BaseController{

	/**
	 * 
	 * 功能描述：所有搭配,当有参数时显示详情页
	 * 作        者：尹东东
	 * 创建时间：2013-6-2 下午3:03:37
	 * 参       数:搭配id,没有参数的时候显示所有
	 * U R L:/style/id
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before({CommonsInterceptor.class,CacheInterceptor.class})
	public void index() {
		String id = getPara();
		if(StringUtils.isEmpty(id)){
			setAttr("api", "/api/style");
			render("index.html");
		}else {
			Style style = Style.getStyle(id);
			if(style == null){
				renderError(404);
			}else {
				Page<SimilarStyles> similarStyles = SimilarStyles.getSimilarStyles(style.getStr("id"));
				setAttr("style", style);
				setAttr("similarStyles", similarStyles.getList());
				render("detail/style.html");
			}
		}
	}
	
	/**
	 * 
	 * 功能描述：主题搭配
	 * 作        者：尹东东
	 * 创建时间：2013-6-4 下午7:55:08
	 * 参       数:
	 * U R L:/style/theme
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before(CommonsInterceptor.class)
	public void theme(){
		setAttr("api", "/api/style");
		setAttr("pname", "type");
		setAttr("pvalue", Style.StyleType.THEME.ordinal());
		render("index.html");
	}
	
	/**
	 * 
	 * 功能描述：明星/街拍达人搭配
	 * 作        者：尹东东
	 * 创建时间：2013-6-4 下午7:57:12
	 * 参       数:
	 * U R L:/style/star
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before(CommonsInterceptor.class)
	public void star(){
		String lg = getPara(0);
		String l = getPara(1);
		if(StringUtils.isEmpty(lg) && StringUtils.isEmpty(l)){
			setAttr("api", "/api/style");
		}else if(StringUtils.isNotEmpty(lg) && StringUtils.isNotEmpty(l)){ //标签组-标签
			setAttr("api", "/api/style/"+lg+"-"+l);
		}else if(StringUtils.isNotEmpty(lg) && StringUtils.isEmpty(l)){//标签组-0
			setAttr("api", "/api/style/"+lg);
		}else if(StringUtils.isNotEmpty(l) && StringUtils.isEmpty(lg)){//0-标签
			setAttr("api", "/api/style/0-"+l);
		}
		setAttr("pname", "type");
		setAttr("pvalue", Style.StyleType.STAR.ordinal());
		render("index.html");
	}
	
	/**
	 * 
	 * 功能描述：单品组合搭配
	 * 作        者：尹东东
	 * 创建时间：2013-6-4 下午7:57:36
	 * 参       数:
	 * U R L:
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before({CommonsInterceptor.class,CacheInterceptor.class})
	public void single(){
		renderText("正在开发中。。。");
	}
	
	/**
	 * 
	 * 功能描述：搭配单品项页
	 * 作        者：尹东东
	 * 创建时间：2013-5-28 下午5:38:49
	 * 参       数:搭配id，搭配单品序号
	 * U R L:/items/id-index?
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before({CommonsInterceptor.class,CacheInterceptor.class})
	public void items() {
		String styleId = getPara(0);
		int sequence = getParaToInt(1,1);
		if(StringUtils.isEmpty(styleId)){
			redirect("/",false);
		}else {
			Style style = Style.getStyle(styleId);
			if(style == null){
				renderError(404);
			}else {
				List<StyleItems> styleItems = style.get("styleItems");
				StyleItems item = styleItems.get(sequence-1);
				item.put("selected", 1);
				style.put("similarItems",SimilarItems.getSimilarItems(item.getStr("image_id")));
				setAttr("style", style);
				render("detail/style_items.html");
			}
		}
	}
	
	/**
	 * 
	 * 功能描述：获取创建搭配时的单品数据
	 * 作        者：尹东东
	 * 创建时间：2013-6-5 下午4:44:51
	 * 参       数:1、上装；2、下装；3、包包；4、配饰；5、鞋子
	 * U R L:/singles/type  1.2.3.4.5
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before({CommonsInterceptor.class,CacheInterceptor.class})
	public void singles() {
		int type = getParaToInt(0, -1);
		String select = "select img.*";
		String sqlExceptSelect = "";
		switch (type) {
		case 1:
			sqlExceptSelect = "from (select i.id,i.description,i.waterfall_url,i.type,i.price,i.source,i.waterfall_width,i.waterfall_height,si.style_id " +
					" from image as i inner join style_items as si on si.image_id=i.id group by i.id) as img" +
					" inner join label_group_image as lgi on lgi.image_id=img.id " +
					" where lgi.label_group_id='100093' " +
					" order by rand()";
			renderJson(Image.dao.paginate(getParaToInt("page", 1), getParaToInt("pageSize", 10), select, sqlExceptSelect));
			break;
		case 2:
			sqlExceptSelect = "from (select i.id,i.description,i.waterfall_url,i.type,i.price,i.source,i.waterfall_width,i.waterfall_height,si.style_id " +
					" from image as i inner join style_items as si on si.image_id=i.id group by i.id) as img" +
					" inner join label_group_image as lgi on lgi.image_id=img.id " +
					" where (lgi.label_group_id='100089' or lgi.label_group_id='100091') " +
					" order by rand()";
			renderJson(Image.dao.paginate(getParaToInt("page", 1), getParaToInt("pageSize", 10), select, sqlExceptSelect));
			break;
		case 3:
			sqlExceptSelect = "from (select i.id,i.description,i.waterfall_url,i.type,i.price,i.source,i.waterfall_width,i.waterfall_height,si.style_id " +
					" from image as i inner join style_items as si on si.image_id=i.id group by i.id) as img" +
					" inner join category_image as ci on ci.image_id=img.id " +
					" where ci.category_id='100002' " +
					" order by rand()";
			renderJson(Image.dao.paginate(getParaToInt("page", 1), getParaToInt("pageSize", 10), select, sqlExceptSelect));
			break;
		case 4:
			sqlExceptSelect = "from (select i.id,i.description,i.waterfall_url,i.type,i.price,i.source,i.waterfall_width,i.waterfall_height,si.style_id " +
					" from image as i inner join style_items as si on si.image_id=i.id group by i.id) as img" +
					" inner join category_image as ci on ci.image_id=img.id " +
					" where ci.category_id='100003' " +
					" order by rand()";
			renderJson(Image.dao.paginate(getParaToInt("page", 1), getParaToInt("pageSize", 10), select, sqlExceptSelect));
			break;
		case 5:
			sqlExceptSelect = "from (select i.id,i.description,i.waterfall_url,i.type,i.price,i.source,i.waterfall_width,i.waterfall_height,si.style_id " +
					" from image as i inner join style_items as si on si.image_id=i.id group by i.id) as img" +
					" inner join category_image as ci on ci.image_id=img.id " +
					" where ci.category_id='100001' " +
					" order by rand()";
			renderJson(Image.dao.paginate(getParaToInt("page", 1), getParaToInt("pageSize", 10), select, sqlExceptSelect));
			break;
		default:
			renderNull();
			break;
		}
	}
	
	/**
	 * 
	 * 功能描述：创建搭配页
	 * 作        者：尹东东
	 * 创建时间：2013-6-2 下午3:47:05
	 * 参       数:搭配类型 0、单品组合搭配；1、明星/街拍达人搭配；2、主题搭配
	 * U R L:/style/create/0
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before({AuthInterceptor.class,CommonsInterceptor.class})
	public void create(){
		String id = getPara();
		if(StringUtils.isEmpty(id)){
			renderNull();
		}else {
			TokenManager.createToken(this, tokenName, 0);
			List<Label> labels = Label.dao.find("select l.id,l.name,l.hot from label as l " +
					" inner join label_group_label as lgl on lgl.label_id=l.id " +
					" where lgl.label_group_id=?", "100052");
			setAttr("templateMenus", labels);
			render("style/theme.html");
		}
	}

	/**
	 * 
	 * 功能描述：发布搭配
	 * 作        者：尹东东
	 * 创建时间：2013-6-2 下午3:47:20
	 * 参       数:
	 * U R L:/style/publish?content=xx&template_id=xx&view_items=[{item_id=xx},{item_id=xx}]
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	@Before({AuthInterceptor.class,POST.class})
	public void publish(){
		if(TokenManager.validateToken(this, tokenName)){
			String content = getPara("content");
			String templateId = getPara("template_id");
			JSONArray jsonArray = JSON.parseArray(getPara("view_items"));
			User user = SessionContext.get().user();
			Image template = Image.getImage("id", templateId);
			if(template != null){
				//保存主图
				Image image = new Image();
				image.set("description", content);
				image.set("url", "0");
				image.set("check_state", Image.ImageState.SHOW.ordinal());
				image.set("check_time", DateUtil.getNowDateTime());
				image.set("type", Image.ImageType.THEME.ordinal());
				image.set("user_id", user.getStr("id"));
				Image.saveImage(image);
				
				//创建主图搭配
				Style style = new Style();
				style.set("image_id", image.getStr("id"));
				style.set("check_state", Style.StyleState.SHOW.ordinal());
				style.set("check_time", DateUtil.getNowDateTime());
				style.set("user_id", user.getStr("id"));
				style.set("description", content);
				Style.saveStyle(style);
				List additionImageList = new ArrayList();
				for(int j=0;j<jsonArray.size();j++){
					JSONObject itemObj = jsonArray.getJSONObject(j);
					Image item = Image.getImage("id", itemObj.getString("item_id"));
					if(item != null){
						StyleItems styleItem = new StyleItems();
						styleItem.set("style_id", style.getStr("id"));
						styleItem.set("image_id", itemObj.getString("item_id"));
						styleItem.set("sequence", j+1);
						StyleItems.saveStyleItems(styleItem);
//						additionImageList.add(new String[]{itemObj.getString("left"),itemObj.getString("top"),
//								itemObj.getString("width"),itemObj.getString("height"),
//								ImageUtil.getLocalPath(item.getStr("waterfall_url"))});
					}else {
						logger.error("搭配单品必须选择");
						throw new RuntimeException("搭配单品必须选择");
					}
				}
				
//				String negativeImagePath = ImageUtil.getLocalPath(template.getStr("url"));
		    	
		    	//try {
		    		String dir = SystemConfig.getValue("img_dir") + "/"+image.getStr("id");
		    		
		    		String toPath = dir+"_normal.jpeg";
					//new OperateImage().mergeImageList(negativeImagePath, additionImageList,"jpg", toPath);
//					image.set("url", ImageUtil.getNetPath(toPath));
					
					String detail_url = dir+"_detail.jpeg";
					String waterfall_url = dir+"_waterfall.jpeg";
					String similar_url = dir+"_similar.jpeg";
					
//					JSONObject jsonObj = ImageUtil.saveImage(toPath, similar_url, ImageUtil.SIMILAR_WIDTH, ImageUtil.SIMILAR_HEIGHT);
//					image.set("similar_url", jsonObj.getString("url"));
//					image.set("similar_width", jsonObj.getString("width"));
//					image.set("similar_height", jsonObj.getString("height"));
//					
//					jsonObj = ImageUtil.saveImage(toPath, waterfall_url, ImageUtil.WATERFALL_WIDTH, null);
//					image.set("waterfall_url", jsonObj.getString("url"));
//					image.set("waterfall_width", jsonObj.getString("width"));
//					image.set("waterfall_height", jsonObj.getString("height"));
//					
//					jsonObj = ImageUtil.saveImage(toPath, detail_url, ImageUtil.DETAIL_WIDTH, null);
//					image.set("detail_url", jsonObj.getString("url"));
//					image.set("detail_width", jsonObj.getString("width"));
//					image.set("detail_height", jsonObj.getString("height"));
					
					image.update();
					
					renderJson(ActionUtils.result(ActionUtils.CODE_200, ActionUtils.SUCCESS,style.getStr("id")));
//				} catch (IOException e) {
//					e.printStackTrace();
//					logger.error("搭配单品必须选择",e);
//					throw new RuntimeException("生成搭配图片出错");
//				}
			}else {
				renderJson(ActionUtils.result(ActionUtils.CODE_100, ActionUtils.FAILED));
			}
		}else {
			renderJson(ActionUtils.result(ActionUtils.CODE_100, "不可以重复提交"));
		}
	}
}
